package com.tianbao54.concurrent.cyclicbarrier;

import java.util.Random;
import java.util.concurrent.*;

public class CyclicBarrierTest {


    public static void main(String[] args) {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        ExecutorService service = Executors.newFixedThreadPool(3);
        service.submit(new Job(cyclicBarrier,"张三"));
        service.submit(new Job(cyclicBarrier,"李四"));
        service.submit(new Job(cyclicBarrier,"王五"));

        service.shutdown();
    }

    static class Job implements Runnable {

        private final CyclicBarrier cyclicBarrier;
        private final String name;

        Job (CyclicBarrier cyclicBarrier,String name) {
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
        }

        @Override
        public void run() {

            try {
                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                System.out.println("3人组开始行动准备去吃饭，当前[" + name + "] 已经到达集合点，当前已有[" + (cyclicBarrier.getNumberWaiting() + 1) + "]个人到达");
                cyclicBarrier.await();
                System.out.println("开始吃饭....");

                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                System.out.println("3人组开始行动准备去看电影，当前[" + name + "] 已经到达集合点，当前已有[" + (cyclicBarrier.getNumberWaiting() + 1) + "]个人到达");
                cyclicBarrier.await();
                System.out.println("开始看电影....");

                TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                System.out.println("3人组开始行动准备去钓鱼，当前[" + name + "] 已经到达集合点，当前已有[" + (cyclicBarrier.getNumberWaiting() + 1) + "]个人到达");
                cyclicBarrier.await();
                System.out.println("开始钓鱼....");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
